package cn.edu.swu.wn.io;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {

    public static void ensureDirectoryExists(String dirPath) {
        if (dirPath == null || dirPath.isEmpty()) {
            return;
        }

        File directory = new File(dirPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }                               //确保保存目录的存在

    public static void saveImage(String url, String savePath) throws IOException{
        File saveFile = new File(savePath);
        ensureDirectoryExists(saveFile.getParent());

        URL imageUrl = new URL(url);
        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
    //获取时间
    public static void appendLog(String log) {
        // 获取当前时间并格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());

        // 构建完整的日志信息
        String fullLog = time + " " + log + "\n";

        try (FileWriter fw = new FileWriter("download_log.txt", true);
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(fullLog);
        } catch (IOException e) {
            System.err.println("日志记录失败: " + e.getMessage());
        }
    }

}
